
export function createUrl(data: BlobPart) {
    return URL.createObjectURL(new Blob([data]));
}

export function formatPrice(price: number) {
    return (price / 100).toFixed(2)
}

export function formatDate(timestamp: number) {
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const date2 = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const sec = date.getSeconds();
    return `${year}-${month}-${date2} ${hour}:${minute}:${sec}`;
}


export function formatSize(size: number) {
    if (size < 1024) {
        return `${size}Byte`;
    } else if (size < (1024 * 1024)) {
        return `${(size / 1024).toFixed(2)}KB`;
    } else if (size < (1024 * 1024 * 1024)) {
        return `${(size / 1024 / 1024).toFixed(2)}MB`;
    } else {
        return `${size}Byte`;
    }
}

export function nullDefault<T>(v: T | null, def: T) {
    if (v == null) {
        return def;
    }
    return v;
}

export function formatPlayTime(n: number) {
    const h = Math.floor(n / 3600);
    const m = Math.floor( (n % 3600) / 60 );
    const s = n % 60;
    return `${h}:${m}:${s}`;
}

export function parsePlayTime(date: Date) {
    const h = date.getHours();
    const m = date.getMinutes();
    const s = date.getSeconds();
    return h * 3600 + m * 60 + s;
}

export function saveFile(name: string, content: BlobPart) {
    const blob = new Blob([content]);
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = name;
    link.click();
    URL.revokeObjectURL(link.href);
}
